//
//  LoginViewController.m
//  Feeder
//
//  Created by Diego Acosta on 7/5/10.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import "LoginViewController.h"
#import "TextFieldTableViewCell.h"
#import "ClientLogin.h"
#import "FeederAppDelegate.h"
#import "UserDefaultsHelper.h"

#define kTableViewRows 2
#define kTableViewUsernameRow 0
#define kTableViewPasswordRow 1

#define kCredsUsernameKey @"username"
#define kCredsPasswordKey @"password"

@implementation LoginViewController

@synthesize navBar;
@synthesize tableView;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	[super viewDidLoad];
	
	// view title.
	navBar.topItem.title = @"Feeder";
	navBar.topItem.prompt = @"Please enter your Google credentials";
	
	NSArray * keys = [NSArray arrayWithObjects:kCredsUsernameKey, kCredsPasswordKey, nil];
	NSArray * values = [NSArray arrayWithObjects:[UserDefaultsHelper username], @"", nil];
	
	// init resources.
	creds = [[NSMutableDictionary alloc] initWithObjects:values
												 forKeys:keys];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	
	// Release any retained subviews of the main view.
	self.navBar = nil;
	self.tableView = nil;
}

- (void)viewWillAppear:(BOOL)animated {
	
	[super viewWillAppear:animated];
	
	NSUInteger row = kTableViewUsernameRow;
	
	// check if username was stored on userdefs.
	if ([[creds objectForKey:kCredsUsernameKey] length] > 0) {
		row = kTableViewPasswordRow;
	}
	
	NSIndexPath * idx = [NSIndexPath indexPathForRow:row inSection:0];
	TextFieldTableViewCell * cell = (TextFieldTableViewCell *)[self.tableView cellForRowAtIndexPath:idx];
	
	// select a row.
	[cell.textField becomeFirstResponder];
}

#pragma mark -
#pragma mark UITextFieldDelegate methods

- (void)textFieldDidEndEditing:(UITextField *)textField {
	
	TextFieldTableViewCell * cell = (TextFieldTableViewCell *)textField.superview.superview;
	NSIndexPath * idx = [self.tableView indexPathForCell:cell];
	
	if (idx.row == kTableViewUsernameRow) {
		
		[creds setValue:cell.textField.text forKey:kCredsUsernameKey];
	}
	else {
		
		[creds setValue:cell.textField.text forKey:kCredsPasswordKey];
	}
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	
	// make sure to save changes on the last textfield.
	[self performSelector:@selector(textFieldDidEndEditing:) withObject:textField];
	
	// make request.
	ClientLogin * clientLogin = [[ClientLogin alloc] init];
	
	[clientLogin setDelegate:self];
	[clientLogin submitWithUsername:[creds objectForKey:kCredsUsernameKey]
						andPassword:[creds objectForKey:kCredsPasswordKey]];
	
	return NO;
}

#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	TextFieldTableViewCell * cell = (TextFieldTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
	
	// select textfield.
	[cell.textField becomeFirstResponder];
}

#pragma mark -
#pragma mark UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	return kTableViewRows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

	static NSString * cellIdentifier = @"TextFieldCell";
	TextFieldTableViewCell * cell;
	
	cell = (TextFieldTableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {

        // .xib top-level objects.
        NSArray * obj = [[NSBundle mainBundle] loadNibNamed:@"TextFieldTableViewCell"
													  owner:self
													options:nil];
		
		// keep the first object (custom cell).
		cell = [obj objectAtIndex:0];
		
		// set-up once.
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.textField.returnKeyType = UIReturnKeyGo;
		cell.textField.delegate = self;
	}
	
	if (indexPath.row == kTableViewUsernameRow) {
		
		cell.label.text = @"Username";
		cell.textField.text = [creds objectForKey:kCredsUsernameKey];
		cell.textField.placeholder = @"example@gmail.com";
		cell.textField.keyboardType = UIKeyboardTypeEmailAddress;
		cell.textField.autocorrectionType = UITextAutocorrectionTypeNo;
	}
	else {
		cell.label.text = @"Password";
		cell.textField.text = [creds objectForKey:kCredsPasswordKey];
		cell.textField.placeholder = @"Required";
		cell.textField.keyboardType = UIKeyboardTypeDefault;
		cell.textField.secureTextEntry = YES;
	}
	
	return cell;
}

#pragma mark -
#pragma mark ClientLoginDelegate methods

- (void)loginFailedWithError:(NSError *)error {

	UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Login Failed"
													 message:@"The username or password you entered is incorrect."
													delegate:nil
										   cancelButtonTitle:@"OK"
										   otherButtonTitles:nil];
	[alert show];
	[alert release];
}

- (void)loginSucceeded:(NSDictionary *)response {

	// store creds on user defaults.
	[UserDefaultsHelper setUsername:[creds objectForKey:kCredsUsernameKey]];
	[UserDefaultsHelper setAuth:[response objectForKey:@"Auth"]];
	
	// notify we're going to load all data.
	FeederAppDelegate * delegate = (FeederAppDelegate *)[[UIApplication sharedApplication] delegate];
	
	delegate.loadAllData = YES;
	
	// hide login window.
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -

- (void)dealloc {
	
	[navBar release];
	[tableView release];
	[creds release];
    [super dealloc];
}

@end
